package com.cong.project.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cong.project.common.ErrorCode;
import com.cong.project.exception.BusinessException;
import com.cong.project.model.entity.*;
import com.cong.project.model.enums.CollectStatusEnum;
import com.cong.project.model.enums.ContentTypeEnum;
import com.cong.project.model.enums.LikeStatusEnum;
import com.cong.project.model.request.ProductAddRequest;
import com.cong.project.model.request.ProductSearchRequest;
import com.cong.project.model.request.TokenUserRequest;
import com.cong.project.model.vo.ProductDetailVo;
import com.cong.project.model.vo.ProductVo;
import com.cong.project.service.*;
import com.cong.project.mapper.ProductMapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author 86188
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2022-11-02 14:28:15
*/
@Service
public class ProductServiceImpl extends MPJBaseServiceImpl<ProductMapper, Product>
    implements ProductService{
    @Resource
    private ProductImgDetailService productImgDetailService;
    @Resource
    private LikeNumService likeNumService;
    @Resource
    private LikeService likeService;
    @Resource
    private CollectService collectService;
    @Resource
    private CollectNumService collectNumService;
    @Override
    public IPage<ProductVo> getProductList(ProductSearchRequest productSearchRequest, TokenUserRequest tokenUserRequest) {
        Long userId = tokenUserRequest.getId();
        MPJLambdaWrapper<ProductVo> wrapper = new MPJLambdaWrapper<ProductVo>()
                .selectAll(Product.class)
                .eq(Product::getCategories,productSearchRequest.getCategories())
                .selectAs(CollectNum::getCollectNum,"collectNum")
                .selectAs(LikeNum::getLikeNum,"thumbNum")
                //获取商品的收藏数量
                .leftJoin(CollectNum.class,left->{
                    left.eq(CollectNum::getContentId,Product::getId).eq(CollectNum::getType, ContentTypeEnum.PRODUCT.getCode());
                    return left;
                })
                //获取帖子的点赞数量
                .leftJoin(LikeNum.class,left->{
                    left.eq(LikeNum::getContentId,Product::getId).eq(LikeNum::getType,ContentTypeEnum.PRODUCT.getCode());
                    return left;
                });
        IPage<ProductVo> productPage = this.selectJoinListPage(new Page<>(productSearchRequest.getPage(), productSearchRequest.getRows()), ProductVo.class, wrapper);
        
        for (ProductVo record : productPage.getRecords()) {
            Likes likeResult = likeService.getOne(new LambdaQueryWrapper<Likes>().eq(Likes::getContentId, record.getId())
                    .eq(Likes::getType, ContentTypeEnum.PRODUCT.getCode())
                    .eq(Likes::getUserId, userId));
            Collect collectResult = collectService.getOne(new LambdaQueryWrapper<Collect>().eq(Collect::getContentId, record.getId())
                    .eq(Collect::getCollectType, ContentTypeEnum.PRODUCT.getCode())
                    .eq(Collect::getUserId, userId));
            //是否存在点赞记录
            if (likeResult==null){
                record.setHaveThumb(false);
            }else {
                //已点赞
                if (likeResult.getLikeStatus()== LikeStatusEnum.IS_LIKE.getCode()){
                    record.setHaveThumb(true);
                }else {
                    record.setHaveThumb(false);
                }
            }
            //是否存在收藏记录
            if (collectResult==null){
                record.setHaveCollect(false);
            }else {
                //已收藏
                if (collectResult.getCollectStatus()== CollectStatusEnum.IS_COLLECT.getCode()){
                    record.setHaveCollect(true);
                }else {
                    record.setHaveCollect(false);
                }
            }
        }
        return productPage;
        
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProduct(ProductAddRequest productAddRequest, TokenUserRequest tokenUserRequest) {

        String name = productAddRequest.getName();
        if (StringUtils.isBlank(name)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品名字不能为空");
        }
        BigDecimal price = productAddRequest.getPrice();
        if (price==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品价格不能为空");
        }
        Integer inventory = productAddRequest.getInventory();
        if (inventory<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"设置下库存，空咋发货");
        }
        String address = productAddRequest.getAddress();
        if (StringUtils.isBlank(address)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请填写你的发货地址");
        }

        Long categories = productAddRequest.getCategories();
        if (categories<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"分类为空，你tm在开挂？");
        }
        String describe = productAddRequest.getDescribes();
        if (StringUtils.isBlank(describe)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"描述不能为空，否则人家不知道你卖啥噢");
        }
        List<String> productImages = productAddRequest.getProductImages();
        if (productImages.size()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不发几张图片人家怎么知道你卖什么！");
        }

        Product product = new Product();
        if (StringUtils.isBlank(product.getDefaultImg())){
            //无默认图片，将原图片数组的第一张设置为默认图片
            product.setDefaultImg(productImages.get(0));
        }
        BeanUtils.copyProperties(productAddRequest,product);
        product.setUserId(tokenUserRequest.getId());
        boolean save = this.save(product);
        if (save){
            List<ProductImgDetail> productImgDetails = new ArrayList<>();
            for (String productImage : productImages) {
                ProductImgDetail productImg = new ProductImgDetail();
                productImg.setImgUrl(productImage);
                productImg.setProductId(product.getId());
                productImgDetails.add(productImg);
            }
            //批量保存商品图片信息
            productImgDetailService.saveBatch(productImgDetails);
            likeService.saveThumbCollect(product.getId(),ContentTypeEnum.PRODUCT.getCode());
            return true;
        }
        return false;
    }

    @Override
    public ProductDetailVo getProductDetail(Long productId, TokenUserRequest tokenUserRequest) {

        Long userId = tokenUserRequest.getId();
        MPJLambdaWrapper<ProductDetailVo> wrapper = new MPJLambdaWrapper<ProductDetailVo>()
                .selectAll(Product.class)
                .eq(Product::getId,productId)
                .selectAs(CollectNum::getCollectNum,"collectNum")
                .selectAs(LikeNum::getLikeNum,"thumbNum")
                //获取商品的收藏数量
                .leftJoin(CollectNum.class,left->{
                    left.eq(CollectNum::getContentId,Product::getId).eq(CollectNum::getType, ContentTypeEnum.PRODUCT.getCode());
                    return left;
                })
                //获取帖子的点赞数量
                .leftJoin(LikeNum.class,left->{
                    left.eq(LikeNum::getContentId,Product::getId).eq(LikeNum::getType,ContentTypeEnum.PRODUCT.getCode());
                    return left;
                });
        ProductDetailVo productPage = this.selectJoinOne( ProductDetailVo.class, wrapper);

            Likes likeResult = likeService.getOne(new LambdaQueryWrapper<Likes>().eq(Likes::getContentId, productPage.getId())
                    .eq(Likes::getType, ContentTypeEnum.PRODUCT.getCode())
                    .eq(Likes::getUserId, userId));
            Collect collectResult = collectService.getOne(new LambdaQueryWrapper<Collect>().eq(Collect::getContentId, productPage.getId())
                    .eq(Collect::getCollectType, ContentTypeEnum.PRODUCT.getCode())
                    .eq(Collect::getUserId, userId));
            //是否存在点赞记录
            if (likeResult==null){
                productPage.setHaveThumb(false);
            }else {
                //已点赞
                if (likeResult.getLikeStatus()== LikeStatusEnum.IS_LIKE.getCode()){
                    productPage.setHaveThumb(true);
                }else {
                    productPage.setHaveThumb(false);
                }
            }
            //是否存在收藏记录
            if (collectResult==null){
                productPage.setHaveCollect(false);
            }else {
                //已收藏
                if (collectResult.getCollectStatus()== CollectStatusEnum.IS_COLLECT.getCode()){
                    productPage.setHaveCollect(true);
                }else {
                    productPage.setHaveCollect(false);
                }
            }
        List<ProductImgDetail> productImgDetails = productImgDetailService.list(new LambdaQueryWrapper<ProductImgDetail>().eq(ProductImgDetail::getProductId, productId));
        if (CollectionUtils.isNotEmpty(productImgDetails)){
            List<String> collect = productImgDetails.stream().map(ProductImgDetail::getImgUrl).collect(Collectors.toList());
            productPage.setImageList(collect);
        }
        return productPage;
    }

}




